import { createRouter, createWebHistory } from 'vue-router'
import AdminView from '@/views/AdminView.vue'
import VisitorView from '@/views/VisitorView.vue'
import HomeView from '@/views/HomeView.vue'
import LoginView from '@/views/LoginView.vue'
import AppLayout from '@/components/AppLayout.vue'
import Statistics from '@/views/StatisticsView.vue'
import VisitorComment from '@/views/VisitorComment.vue'
import { useUserStore } from '@/stores/user'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      component: HomeView,
    },
    {
      path: '/login',
      component: LoginView,
    },
    {
      path: '/admin',
      component: AppLayout,
      children: [
        {
          path: 'home',
          component: AdminView,
        },
        {
          path: 'Statistics',
          component: Statistics,
        },
      ],
      meta: { requiresAuth: true, role: 'admin' },
    },
    {
      path: '/visitor',
      component: AppLayout,
      children: [
        {
          path: 'home',
          component: VisitorView,
        },
        {
          path: 'Comment',
          component: VisitorComment,
        },
      ],
      meta: { requiresAuth: true, role: 'visitor' },
    },
  ],
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  const userStore = useUserStore()

  // 检查路由是否需要认证
  if (to.meta.requiresAuth) {
    // 如果用户未登录，重定向到登录页
    if (!userStore.isLoggedIn) {
      next({ path: '/login' })
      return
    }

    // 检查用户角色是否匹配
    if (to.meta.role === 'admin' && !userStore.isAdmin()) {
      // 如果用户不是管理员但尝试访问管理员页面
      if (userStore.isVisitor()) {
        next({ path: '/visitor' })
      } else {
        next({ path: '/login' })
      }
      return
    } else if (to.meta.role === 'visitor' && !userStore.isVisitor()) {
      // 如果用户不是游客但尝试访问游客页面
      if (userStore.isAdmin()) {
        next({ path: '/admin' })
      } else {
        next({ path: '/login' })
      }
      return
    }
  }

  // 如果用户已登录且尝试访问登录页，重定向到对应的首页
  if (to.path === '/login' && userStore.isLoggedIn) {
    if (userStore.isAdmin()) {
      next({ path: '/admin' })
    } else if (userStore.isVisitor()) {
      next({ path: '/visitor' })
    }
    return
  }

  // 其他情况正常放行
  next()
})

export default router
